'use strict';

const WANTU = require('./wantu');
const wantu = new WANTU('23246224', 'c1253bd619fad8ea02d68c283debdf2a');  //填入ak，sk
var request = require('request');//获取线上图片转成本地的
var fs = require('fs');


/*
 uploadPolicy 必填，上传策略，json格式，具体参见API说明文档
 filepath 必填，本地文件路径
 dir 必填，上传到文件夹路径；以’/‘开头，不能以’/‘结尾；根目录为’/’
 meta 必填，用户自定义的文件meta信息，没有为""
 _var 必填，魔法变量，没有为""
 callback 必填，回调
 */


 module.exports = function (namespace,dir) {

    var getImgwtUrlByUrl=function(otherurl){
      var uploadPolicy = {
       namespace: namespace,
       expiration: -1
   };
   var timestamp=new Date().valueOf();
   var img_filename = "\/"+timestamp+".jpg"; 
   var filePath =__dirname+'/images'+img_filename;
   console.log(filePath);
   var dir = dir;
   var meta = '';
   var _var = '';
   var callback = function (err,res) {
      return new Promise(function(resolve,reject){

        if(err){
          throw err;
      }
      if(res.statusCode == 200){
            fs.unlinkSync(filePath);
          var imgUrl=JSON.parse(res.data).url;
          return resolve(imgUrl);
      }

  })
  };
  var img_src = otherurl; 

  request(img_src).pipe(fs.createWriteStream(filePath))
  .on('close',function(){
      wantu.singleUpload(uploadPolicy, filePath, dir, meta, _var, callback)
  });   
}

return {
  getImgwtUrlByUrl:getImgwtUrlByUrl
}
}
